﻿using Abp.Net.Sms;
using Abp.Runtime.Caching;
using Partner.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HCD.DomainServices.Cloud
{
    public class SMSManager : EnterpriseDomainServiceBase, ISMSManager
    {
        public ISmsSender SmsSender { get; set; }
        public ICacheManager CacheManager { get; set; }
        public async Task CheckVerificationCode(string PhoneNumber, string VerificationCode)                                  
        {
            if (string.IsNullOrWhiteSpace(VerificationCode))
                throw new BizException("验证码无效");         
            var code = await CacheManager.GetCache<string, string>(Const.RedisConst.SMSVerificationCode).GetOrDefaultAsync(PhoneNumber);
            if (string.IsNullOrEmpty(code))
            {
                throw new BizException("验证码超时");
            }
            else if (code != VerificationCode)
            {
                throw new BizException("验证码错误");
            }
        }                                   
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="PhoneNumber">手机号</param>
        /// <param name="flag">再次发送标记：0忽略，1允许有效期内再次发送</param>
        /// <returns></returns>
        public async Task<string> SendVerificationCode(string PhoneNumber, int flag = 0)
        {
            if (!PhoneNumber.IsMobile())
                throw new BizException("非法手机号");
            var flushcount = await CacheManager.GetCache<string,int>(Const.RedisConst.AntiFlush).GetAsync(PhoneNumber, key =>Task.FromResult(0));
            if (flushcount > 2)
                throw new BizException("验证码数量超过上限，12H内只能发送3次");  
            else if (flushcount > 0 && flag == 0)//已发送过一次，提示是否再次发送
                throw new BizException("12H内已有登录验证码，是否重新发送？", ErrorCodeEnum.Confrim); ;
            Random rad = new Random();
            var value = ComFunc.GetRandom().ToString();
            var key = Guid.NewGuid().ToString();
            //SmsSender.Send(PhoneNumber, "", new string[] { value });
            value = "123456";
            await CacheManager.GetCache<string,string>(Const.RedisConst.SMSVerificationCode).SetAsync(PhoneNumber, value);
            await CacheManager.GetCache<string,int>(Const.RedisConst.AntiFlush).SetAsync(PhoneNumber, ++flushcount);
            return key;
        }
    }
}
